package UI;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.SQLException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.Border;

import threads.BaseRunnableBCBS;
import Logic.RoundMath;
import Logic.SQLReader;
import UI.BaseModels.BCBSPanel;
import UI.BaseModels.HeaderLabel;
import UI.BaseModels.PurchaseSellButton;
import UI.BaseModels.ReturnToMainMenuButton;

// TODO: Auto-generated Javadoc
/**
 * The Class TransferPanel.
 */
public class TransferPanel extends BCBSPanel {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -8116582400409912475L;

	/** The to field. */
	private JTextField toField;

	/** The amount field. */
	private JTextField amountField;

	/** The confirm button. */
	private JButton confirmButton;

	/** The message field. */
	private JTextArea messageField;

	/**
	 * Instantiates a new transfer panel.
	 */
	public TransferPanel() {

		HeaderLabel header = new HeaderLabel("Transfer BCBS");
		this.add(header);

		toField = new JTextField();
		toField.setHorizontalAlignment(SwingConstants.CENTER);
		toField.setBounds(51, 102, 202, 20);
		this.add(toField);
		toField.setColumns(10);

		JLabel transfer_BCBStoLabel = new JLabel("To");
		transfer_BCBStoLabel.setHorizontalAlignment(SwingConstants.CENTER);
		transfer_BCBStoLabel.setBounds(129, 77, 46, 14);
		this.add(transfer_BCBStoLabel);

		amountField = new JTextField();
		amountField.setHorizontalAlignment(SwingConstants.CENTER);
		amountField.setBounds(109, 158, 86, 20);
		this.add(amountField);
		amountField.setColumns(10);

		JLabel transfer_BCBSamountLabel = new JLabel("Amount");
		transfer_BCBSamountLabel.setHorizontalAlignment(SwingConstants.CENTER);
		transfer_BCBSamountLabel.setBounds(129, 133, 46, 14);
		this.add(transfer_BCBSamountLabel);

		confirmButton = new PurchaseSellButton("Transfer");
		confirmButton.setLocation(90, 331);
		confirmButton.addActionListener(new BtnTransferBCBSActionListener());
		this.add(confirmButton);

		feedbackLabel.setBounds(0, 300, 305, 25);

		messageField = new JTextArea();
		messageField.setWrapStyleWord(true);
		messageField.setLineWrap(true);
		messageField.setBounds(61, 223, 182, 74);
		messageField.addKeyListener(new KeyListener() {
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					e.consume();
					performTransaction();
				}
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
			}
		});

		Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
		messageField.setBorder(BorderFactory.createCompoundBorder(border,
				BorderFactory.createEmptyBorder(5, 5, 5, 5)));
		this.add(messageField);

		JLabel transfer_BCBSmessageLabel = new JLabel("Message to Recipient");
		transfer_BCBSmessageLabel.setHorizontalAlignment(SwingConstants.CENTER);
		transfer_BCBSmessageLabel.setBounds(76, 198, 152, 14);
		this.add(transfer_BCBSmessageLabel);

		ReturnToMainMenuButton rtmm = new ReturnToMainMenuButton();
		this.add(rtmm);
	}

	private class BtnTransferBCBSActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			performTransaction();
		}
	}
	/**
	 * Resets text fields and enables the confirm-button.
	 */
	@Override
	public void clearFields() {
		messageField.setText("");
		feedbackLabel.setText("");
		amountField.setText("");
		toField.setText("");
		confirmButton.setEnabled(true);
	}

	/**
	 * Enables the transfer-button based on the parameter specified.
	 * 
	 * @param value
	 *            If true enables the button, if false deactivates it.
	 */
	public void enableButton(boolean value) {
		if (value) {
			confirmButton.setEnabled(true);
			messageField.setEnabled(true);
		} else {
			confirmButton.setEnabled(false);
			messageField.setEnabled(false);
		}

	}

	/**
	 * Creates a new Runnable of the type performTransaction, sets it to the
	 * current runnable for the panel, places it in its own thread and runs it.
	 */
	public void performTransaction() {
		enableButton(false);
		runnable = new TransferBCBSRunnable();
		Thread t = new Thread(runnable);
		t.start();
	}

	private class TransferBCBSRunnable extends BaseRunnableBCBS {
		/**
		 * Transfers a specific amount (defined in interface) of BCBS to the
		 * user specified in the text fields for the panel, given the user has
		 * sufficient funds in his or her account.
		 */
		public void run() {
			SQLReader reader = new SQLReader();
			boolean userexists = false;
			String touser = "";
			String message = "";
			double roundedvalue = 0;
			boolean validamount = false;
			boolean invalidinput = false;

			try {
				roundedvalue = RoundMath.round(Double

				.parseDouble(amountField.getText().trim()), 2);
				amountField.setText(String.valueOf(roundedvalue));
				if (roundedvalue > 0) {
					validamount = true;
				}

			} catch (NumberFormatException e) {
				feedback("Please input a valid amount!", false);
				invalidinput = true;
				enableButton(true);

			}
			if (validamount) {
				try {
					touser = toField.getText().trim();
					message = messageField.getText().trim();
					enableButton(false);
					userexists = reader.checkEmail(touser);
					if (!stop) {
						if (message.isEmpty()) {
							message = "Transfer of " + roundedvalue
									+ " BCBS by user "
									+ UI.MainFrame.currentUser.getEmail();
						}
					}
					if (!stop) {
						if (UI.MainFrame.currentUser.getBalance() >= roundedvalue
								&& userexists
								&& !touser
										.equalsIgnoreCase(UI.MainFrame.currentUser
												.getEmail())) {
							reader.performTransaction(reader.getUserID(touser),
									UI.MainFrame.currentUser.getId(),
									roundedvalue, message);
							if (!stop) {
								UI.MainFrame.switchToPanel(
										UI.MainFrame.main_menu, null);
								UI.MainFrame.main_menu.feedback("Transferred "
										+ roundedvalue + " BCBS to user:",
										touser, true);
								clearFields();
							}
						} else if (UI.MainFrame.currentUser.getBalance() < roundedvalue) {
							feedback("Insufficient funds!", false);
							enableButton(true);
						} else if (!userexists) {
							feedback("User does not exist!", false);
							enableButton(true);
						} else if (touser
								.equalsIgnoreCase(UI.MainFrame.currentUser
										.getEmail())) {
							feedback("Cannot transfer to self!", false);
							enableButton(true);
						}
					}
				} catch (SQLException e) {
					if (!stop) {
						feedback("Connection error. Try again!", false);
						enableButton(true);
					}
				}
			} else if (roundedvalue <= 0 && !invalidinput) {
				feedback("Amount must larger than 0!", false);
				enableButton(true);
			}
		}
	}

}